import { isObject , isTureVal} from '../common/tool';
/**
 * 事件总线
 */
export class BUS {
  data: object | undefined | any = {};
  event: object = {};
  constructor(props) {
    if (!isTureVal(props.data) || !isObject(props.data)) {
      this.data = {};
    } else {
      this.data = props.data || {};
    }
  };
  /**
   * 状态数据
   * @param value 设置数据
   */
  setData(value: any) {
    this.data = value;
  }
  /**
   * 注册事件
   * @param type string
   * @param fn function
   * @returns 
   */
  on(type: string, fn: Function){
    if (typeof fn !== 'function') {
      return;
    }
    if (isObject(this.event)) {
      this.event = {};
    }
    if (!Array.isArray(this.event[type])) {
      this.event[type] = [];
    }
    this.event[type].push(fn);
  };
  /**
   * 
   * @param type string
   * @param list list
   * @returns 
   */
  emit(type: string, ...list) {
    if (!Array.isArray(this.event[type])) {
      return;
    }
    const result: any = []
    this.event[type].forEach(async fn => {
      if (typeof fn !== 'function') {
        return;
      }
      result.push(await fn(this.data, ...list))
    });
    return result;
  };
  /**
   * 删除事件
   * @param type string
   */
  off(type: string) {
    this.event[type] = null;
  }
}